<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>图形平移使用的是平移矩阵</title>
    <script src="test.js"></script>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      canvas {
        margin: 50px auto 0;
        display: block;
        background: yellow;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="400px" height="400px"></canvas>

    <script>
      // 1获取webgl
      const canvas = document.getElementById('canvas')
      const gl = canvas.getContext('webgl')

      // 3.定义顶点着色器和片元着色器
      // uniform针对所有顶点生效
      const vsSource = `
        attribute vec4 aPosition;
        uniform mat4 uTranslate;
        void main(){
        gl_Position = uTranslate * aPosition;
        }`
      // uTranslate * aPosition乘的先后顺序要知道
      const fsSource = `
        void main(){
         gl_FragColor = vec4(1.0,0.0,0.0,1.0);
        }`

      // 2.初始化webgl
      const program = initShader(gl, vsSource, fsSource)
      gl.useProgram(program)
      // 4.获取aPosition的值
      const aPosition = gl.getAttribLocation(program, 'aPosition')
      const uTranslate = gl.getUniformLocation(program, 'uTranslate')

      // 构建矩阵函数
      function getTranslateMatrix(x = 0, y = 0, z = 0) {
        return new Float32Array([1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0])
      }

      //向顶点着色器uniform变量u_TranslateMatrix传值

      //   5.创建缓存区
      const points = new Float32Array([-0.5, -0.5, 0.5, -0.5, 0.0, 0.5])
      const buffer = gl.createBuffer()
      if (!buffer) {
        console.log('创建缓冲区对象失败！')
      }
      gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
      gl.bufferData(gl.ARRAY_BUFFER, points, gl.STATIC_DRAW)
      // 5.指定 uniform 的存储地址，四个分量
      gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0)
      gl.enableVertexAttribArray(aPosition)
      // 清除颜色缓冲区
      // gl.clear(gl.COLOR_BUFFER_BIT)
      let x = -1
      function animation() {
        x += 0.01
        if (x > 1) {
          x = -1
        }
        const matrix = getTranslateMatrix(x)
        // gl.vertexAttrib1f(uTranslate, x)
        gl.uniformMatrix4fv(uTranslate, false, matrix)
        gl.drawArrays(gl.TRIANGLES, 0, 3) //重新绘制
        requestAnimationFrame(animation)
      }
      animation()
    </script>
  </body>
</html>
